package com.coldwindblows.blog.controller.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.dto.Types;
import com.coldwindblows.blog.pojo.MetaDo;
import com.coldwindblows.blog.service.IMetaService;

/**
 * Created by ColdWindBlows on 2018/07/06
 *
 */
@Controller
@RequestMapping("admin/links")
@SuppressWarnings("rawtypes")
public class LinksController extends BaseController {
	
	@Autowired
	private IMetaService metaService;
	
	@GetMapping("")
	public String index(Model model) {
		List<MetaDo> metaList = metaService.getMetas(Types.LINK.getType());
		model.addAttribute("links", metaList);
		return "admin/links";
	} 
	
	@PostMapping("/save")
	@ResponseBody
	public RestResponseBo saveLink(@RequestParam String title, @RequestParam String url, @RequestParam String logo, @RequestParam Integer mid, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {
		try {
			MetaDo meta = new MetaDo();
			meta.setName(title);
			meta.setSlug(url);
			meta.setDescription(logo);
			meta.setSort(sort);
			meta.setType(Types.LINK.getType());
			if(null != mid) {
				meta.setMid(mid);
				metaService.updateMeta(meta);
			} else {
				metaService.insertMeta(meta);
			}
		}catch(Exception e) {
			String msg = "友链保存失败";
			return RestResponseBo.fail(msg);
		}
		
		return RestResponseBo.ok();
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public RestResponseBo delete(@RequestParam Integer mid) {
		try {
			metaService.deleteMeta(mid);
		} catch(Exception e) {
			String msg = "友链删除失败";
			return RestResponseBo.fail(msg);
		}
		return RestResponseBo.ok();
	}
	
}
